/**
 * 
 */
package org.mspring.mlog.service.security.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.mspring.mlog.entity.security.Role;
import org.mspring.mlog.service.security.RoleService;
import org.mspring.mlog.service.security.UserService;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Gao Youbo
 * @since 2013-1-11
 * @Description
 * @TODO
 */
@Service
@Transactional
public class RoleServiceImpl extends GenericDao<Role, Long> implements RoleService {

    private static final Logger log = Logger.getLogger(RoleServiceImpl.class);

    @Autowired
    private UserService userService;

    @Override
    public List<Role> getRolesByUser(Long userId) {
        // TODO Auto-generated method stub
        return list("select userRole.PK.role from UserRole userRole where userRole.PK.user.id = ?", userId);
    }

    @Override
    public Role getRoleByName(String name) {
        // TODO Auto-generated method stub
        Object obj = getHibernateTemplate().uniqueResult("select role from Role role where role.name = ?", name);
        return obj == null ? null : (Role) obj;
    }

    @Override
    public boolean checkRoleNameExists(String name, Long id) {
        // TODO Auto-generated method stub
        int count = 0;
        if (id == null) {
            count = getHibernateTemplate().count("select count(*) from Role role where role.name = ?", name);
        } else {
            count = getHibernateTemplate().count("select count(*) from Role role where role.name = ? and role.id <> ?", new Object[] { name, id });
        }
        return count > 0;
    }

    @Override
    public List<Role> findEnabledRole() {
        // TODO Auto-generated method stub
        return list("select role from Role role where role.enabled = ?", true);
    }

    @Override
    public void deleteRole(Long roleId) {
        // TODO Auto-generated method stub
        if (hasUserInRole(roleId)) {
            log.warn("can't delete role, RoleID = " + roleId + ", has some users in this role.");
            return;
        }
        getHibernateTemplate().remove(Role.class, roleId);
        // 删除跟该角色相关联的数据
        getHibernateTemplate().executeUpdate("delete RoleResource roleResource where roleResource.PK.role.id = ?", roleId);
    }

    @Override
    public boolean hasUserInRole(Long roleId) {
        // TODO Auto-generated method stub
        int count = getHibernateTemplate().count("select count(*) from UserRole userRole where userRole.PK.role.id = ?", roleId);
        return count > 0;
    }

}
